package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.dto.OrderInfoDto;
import com.itheima.pojo.Member;
import com.itheima.pojo.OrderSetting;
import com.itheima.redis.RedisUtil;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.OrderMapper;
import com.itheima.pojo.Order;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.DateUtil;
import com.itheima.utils.PayUtils;
import com.itheima.utils.SnowflakeIdWorker;
import com.itheima.vo.OrderSuccessInfoVo;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Resource
    private MemberService memberService;

    @Resource
    private OrderSettingService orderSettingService;

    @Override
    @Transactional
    public Long createOrder(OrderInfoDto orderInfoDto) {
        //1.短信验证码校验
        String code = RedisUtil.get("sms:code:" + orderInfoDto.getTelephone());
        String validateCode = orderInfoDto.getValidateCode();
        if (code==null){
            throw  new RuntimeException("没有发送短信验证码，或验证码已过期，请重新发送！");
        }
        if(code.equals(validateCode)==false){
            throw  new RuntimeException("验证码输入错误！");
        }
        //2.判断是否重复预约
        //2.1根据手机号查找该会员
        //2.2会员该日期已经预约了改套餐
        String orderDate = DateUtil.formatDate(orderInfoDto.getOrderDate());//将日期转换成字符串
        Member member= memberService.findByTelephone(orderInfoDto.getTelephone());
        if (member!=null){
            Order order=this.exists(member.getId(),orderDate);
            if (order!=null){
                throw new RuntimeException("您已预约了，请勿重复预约！");
            }
        }
        //3.当前日期是否可以预约（看是否已经预约满）
        OrderSetting orderSetting = orderSettingService.findByDate(orderDate);
        if (orderSetting==null||orderSetting.getNumber()<=0){
            throw new RuntimeException("当前日期不可预约！");
        }
        if (orderSetting.getNumber()==orderSetting.getReservations()){
            throw new RuntimeException("当前日期预约已满！");
        }
        return doCreateOrder(orderInfoDto,orderSetting,member);

    }

    @Override
    public OrderSuccessInfoVo orderSuccess(String orderId) {
        return this.baseMapper.orderSuccess(orderId);
    }

    @Override
    public Map selectSetmealData() {
        HashMap<String, Object> map = new HashMap<>();
        List<Map> seriesDataList=this.baseMapper.selectSetmealData();
        map.put("seriesData",seriesDataList);
        List<String> legendData = new ArrayList<>();
        for (Map map1 : seriesDataList) {
            legendData.add((String) map1.get("name"));
        }
        map.put("legendData",legendData);
        return map;
    }

    private Order exists(Long memberId, String orderDate) {
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id",memberId);
        queryWrapper.eq("order_date",orderDate);
        return  this.getOne(queryWrapper);
    }

    private Long doCreateOrder(OrderInfoDto orderInfoDto, OrderSetting orderSetting, Member member) {
        //4.预约设置预约数加一,修改数据库
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingService.updateById(orderSetting);
        //5.会员信息维护
        if (member==null){
            member  = new Member();
            member.setCreateDate(new Date());
        }
        member.setIdCard(orderInfoDto.getIdCard());
        member.setName(orderInfoDto.getName());
        member.setSex(orderInfoDto.getSex());
        member.setTelephone(orderInfoDto.getTelephone());
        Long memberId=memberService.saveMember(member);
        //6.预约订单，往订单表添加数据
        Order order = new Order();
        //雪花算法生成id
        order.setOrderNo(String.valueOf(SnowflakeIdWorker.getInstance().nextId()));
        order.setOrderDate(orderInfoDto.getOrderDate());
        order.setMemberId(memberId);
        order.setPayStatus(0);
        order.setSetmealId(orderInfoDto.getSetmealId());
        this.save(order);
        return order.getId();
    }

    @Override
    public String wxPay(String id) {
        //查询订单号和金额
        Order order = this.getById(id);
        if(order==null){
            throw new RuntimeException("订单不存在");
        }
        if(1==order.getPayStatus() ){
            throw  new RuntimeException("订单已支付，请勿重复支付");
        }
        String orderNo = order.getOrderNo();
        //生成订单,支付
        String payOrder = PayUtils.createOrder(orderNo, 1);
        //返回支付结果
        return payOrder;
    }

    @Override
    public void updatePayStatus(Map param) {
        Order order = new Order();
        order.setPayStatus(1);
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_no",param.get("out_trade_no"));
        boolean update = this.update(order, orderQueryWrapper);
    }

    @Override
    public boolean selectPayStatusById(String id) {
        Order order = this.getById(id);
        if(order==null){
            throw new RuntimeException("未生成订单");
        }
        if(1==order.getPayStatus()){
            return true;
        }
        return false;
    }
}